package com.along.htybrowser;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Base64;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebHistoryItem;
import android.webkit.WebIconDatabase;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebView.HitTestResult;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.along.htybrowser.bean.ResourcesBean;
import com.along.htybrowser.databinding.ActivityMainBinding;
import com.along.htybrowser.databinding.DialogDownloadBinding;
import com.along.htybrowser.greendao.tab.FavoriteTab;
import com.along.htybrowser.utils.AutoLog;
import com.along.htybrowser.utils.FileUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 首页
 */
public class MainActivity extends Activity {
    private ActivityMainBinding binding;
    private DialogDownloadBinding downloadBinding;
    InputMethodManager IMM;

    String urlo = "", HTRE = "", ptitle = "", urln = "";
    CustomViewCallback customViewCallback;
    boolean isFullScreen, isManualCheckUpdate = false;

    SharedPreferences sharedPreferences;
    long downloadIdUpdate;
    private List<WebView> list_webView = new ArrayList<>();
    private List<ArrayList<ResourcesBean>> resourcesList = new ArrayList<>();
    private List<String> currentUrlList = new ArrayList<>();//指定窗口下当前加载url地址
    int currentPage;
    int FILECHOOSER_DOWNLOAD_PATH = 3;
    DownloadCompleteReceiver receiver;
    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static int REQUEST_PERMISSION_CODE = 1;
    private WebSettings webSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(PERMISSIONS, REQUEST_PERMISSION_CODE);
            }
        }

        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        IMM = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        FileUtil.initFile(getExternalFilesDir(null).getPath());

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        binding.searchBar.setVisibility(View.GONE);
        binding.buttonPlay.setVisibility(View.GONE);

        binding.buttonTitle.setOnClickListener(new ButtonListener());
        binding.buttonPage.setOnClickListener(new ButtonListener());
        binding.buttonGo.setOnClickListener(new ButtonListener());
        binding.buttonBack.setOnClickListener(new ButtonListener());
        binding.buttonForward.setOnClickListener(new ButtonListener());
        binding.buttonMenu.setOnClickListener(new ButtonListener());
        binding.buttonPlay.setOnClickListener(new ButtonListener());
        binding.buttonSearchPrev.setOnClickListener(new ButtonListener());
        binding.buttonSearchNext.setOnClickListener(new ButtonListener());
        binding.buttonSearchClose.setOnClickListener(new ButtonListener());
        binding.editTextUrl.setVisibility(View.GONE);
        WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());    //获取图标数据库路径
        getDataFromIntent(getIntent());

        binding.editTextUrl.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                loadPage(binding.editTextUrl.getText().toString());
                return true;
            }
            return false;
        });

        binding.editTextSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                list_webView.get(currentPage).findAllAsync(binding.editTextSearch.getText().toString());
                IMM.hideSoftInputFromWindow(binding.editTextSearch.getWindowToken(), 0);
                return true;
            }
            return false;
        });

        binding.editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
                // text 输入框中改变后的字符串信息
                // start 输入框中改变后的字符串的起始位置
                // before 输入框中改变前的字符串的位置 默认为0
                // count 输入框中改变后的一共输入字符串的数量
                list_webView.get(currentPage).findAllAsync(text.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count, int after) {
                // text 输入框中改变前的字符串信息
                // start 输入框中改变前的字符串的起始位置
                // count 输入框中改变前后的字符串改变数量一般为0
                // after 输入框中改变后的字符串与起始位置的偏移量
            }

            @Override
            public void afterTextChanged(Editable edit) {
                // edit 输入结束呈现在输入框中的信息
            }
        });

        receiver = new DownloadCompleteReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(receiver, intentFilter);
    }

    private void setFullScreen() {
        // RelativeLayout1.setVisibility(View.GONE);
        binding.LinearLayout1.setVisibility(View.GONE);
        binding.videoLayout.setVisibility(View.VISIBLE);
        // imageView1.setVisibility(View.VISIBLE);
        // 横屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 设置全屏的相关属性，获取当前的屏幕状态，然后设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // 全屏下的状态码：1098974464
        // 窗口下的状态吗：1098973440
        isFullScreen = true;
    }

    // 退出全屏
    private void quitFullScreen() {
        if (customViewCallback != null) {
            customViewCallback.onCustomViewHidden();    // 隐藏
        }
        // RelativeLayout1.setVisibility(View.VISIBLE);
        binding.LinearLayout1.setVisibility(View.VISIBLE);
        binding.LinearLayout2.setVisibility(View.VISIBLE);
        binding.progressBar1.setVisibility(View.VISIBLE);
        binding.videoLayout.setVisibility(View.GONE);
        // imageView1.setVisibility(View.GONE);
        // 用户当前的首选方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
        // 声明当前屏幕状态的参数并获取
        final WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        isFullScreen = false;
    }

    public ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public final static int FILECHOOSER_RESULTCODE = 1;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("*/*");
        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    /**
     * 界面按钮事件
     */
    class ButtonListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_title:
                    binding.buttonTitle.setVisibility(View.GONE);
                    binding.editTextUrl.setVisibility(View.VISIBLE);
                    break;
                case R.id.button_page:
                    List<String> list_title = new ArrayList<>();
                    for (int i = 0; i < list_webView.size(); i++) {
                        list_title.add(i + 1 + "." + list_webView.get(i).getTitle());
                    }
                    String[] titles = list_title.toArray(new String[list_title.size()]);
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("窗口");
                    builder.setIcon(android.R.drawable.ic_menu_slideshow);
                    builder.setItems(titles, (dialog, which) -> {
                        dialog.dismiss();
                        if (which != currentPage) {
                            binding.webViewLayout.removeAllViews();
                            WebView webView = list_webView.get(which);
                            binding.webViewLayout.addView(webView);
                            binding.buttonPage.setText(which + 1 + "");
                            binding.buttonTitle.setText(webView.getTitle());
                            binding.editTextUrl.setText(webView.getUrl());
                            binding.imageButtonInfo.setImageBitmap(webView.getFavicon());
                            currentPage = which;
                        }
                    });
                    builder.create().show();
                    break;
                case R.id.button_go:
                    list_webView.get(currentPage).loadUrl(binding.editTextUrl.getText().toString());
                    break;
                case R.id.button_back:
                    if (list_webView.get(currentPage).canGoBack()) {
                        int len = list_webView.get(currentPage).copyBackForwardList().getSize();
                        AutoLog.v("显示返回栈长度：" + len);
                        for (int i = 0; i < len; i++) {
                            WebHistoryItem itemAtIndex = list_webView.get(currentPage).copyBackForwardList().getItemAtIndex(i);
                            AutoLog.v("显示返回栈地址：" + itemAtIndex.getUrl());
                            AutoLog.v("显示返回栈标题：" + itemAtIndex.getTitle());
                        }
                        list_webView.get(currentPage).goBack();
                        binding.buttonForward.setEnabled(true);
                    } else {
                        binding.buttonBack.setEnabled(false);
                    }
                    break;
                case R.id.button_forward:
                    if (list_webView.get(currentPage).canGoForward()) {
                        list_webView.get(currentPage).goForward();
                        binding.buttonBack.setEnabled(true);
                    } else {
                        binding.buttonForward.setEnabled(false);
                    }
                    break;
                case R.id.button_menu:
                    MenuDialog();
                    break;
                case R.id.button_play:
                    playVideo();
                    binding.buttonPlay.setVisibility(View.GONE);
                    break;
                case R.id.button_search_prev:
                    list_webView.get(currentPage).findNext(false);
                    break;
                case R.id.button_search_next:
                    list_webView.get(currentPage).findNext(true);
                    break;
                case R.id.button_search_close:
                    binding.editTextSearch.setText("");
                    IMM.hideSoftInputFromWindow(binding.editTextSearch.getWindowToken(), 0);
                    binding.searchBar.setVisibility(View.GONE);
                    break;
            }
        }
    }

    private class MyWebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
            AutoLog.e(Thread.currentThread().getStackTrace()[2] + ": ", url + ", " + userAgent + "," + contentDisposition + ", " + mimeType + ", " + contentLength);
            dialog_download(url, contentDisposition, mimeType, contentLength);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        WebView w = (WebView) v;
        HitTestResult result = w.getHitTestResult();
        HTRE = result.getExtra();
        AutoLog.v("内容菜单", HTRE + " = " + result.getType());
        menu.setHeaderTitle(HTRE);
        if (result.getType() == HitTestResult.IMAGE_TYPE || result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            menu.setHeaderIcon(android.R.drawable.ic_menu_gallery);
            menu.add(0, 0, 0, "查看图片");
            //menu.add(0, 1, 1, "复制图片");
            menu.add(0, 2, 2, "保存图片").setIcon(android.R.drawable.ic_menu_save); // Context menu items do not support icons
            menu.add(0, 3, 3, "复制链接");
            menu.add(0, 4, 4, "屏蔽图片");
            menu.add(0, 5, 5, "隐藏图片");
        } else if (result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
            menu.setHeaderIcon(R.drawable.link);
            menu.add(0, 0, 0, "在新窗口打开链接");
            menu.add(0, 2, 2, "下载");
            menu.add(0, 3, 3, "复制链接");
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                newWindow(HTRE);
                break;
            case 1:
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ContentValues values = new ContentValues(2);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
                values.put(MediaStore.Images.Media.DATA, HTRE);
                Uri imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                ClipData clipData = ClipData.newUri(getContentResolver(), "Image", imageUri);
                clipboardManager.setPrimaryClip(clipData);
                break;
            case 2:
                String mime = URLConnection.getFileNameMap().getContentTypeFor(HTRE);
                AutoLog.e(Thread.currentThread().getStackTrace()[2] + " ", "" + mime);
                if (mime == null) mime = "";
                dialog_download(HTRE, "", mime, 0);
                break;
            case 3:
                clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setPrimaryClip(ClipData.newPlainText("link", HTRE));
                Toast.makeText(getApplicationContext(), "链接已复制", Toast.LENGTH_SHORT).show();
                break;
            case 4:
                DialogBlock(HTRE);
                break;
            case 5:
                String js = "javascript:var imgs=document.getElementsByTagName('img');for(i=0;i<imgs.length;i++){if(imgs[i].src=='" + HTRE + "'){imgs[i].style.display='none';break;}}";
                list_webView.get(currentPage).loadUrl(js);
                break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", keyCode + ", " + event);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isFullScreen) {
                binding.buttonPlay.setVisibility(View.GONE);
                quitFullScreen();
            } else {
                if (list_webView.get(currentPage).canGoBack()) {
                    list_webView.get(currentPage).goBack();
                }
            }
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            list_webView.get(currentPage).findAllAsync(binding.editTextSearch.getText().toString());
            IMM.hideSoftInputFromWindow(binding.editTextSearch.getWindowToken(), 0);
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_F) {
            binding.searchBar.setVisibility(View.VISIBLE);
            binding.editTextSearch.requestFocus();
            list_webView.get(currentPage).findAllAsync(binding.editTextSearch.getText().toString());
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
            binding.searchBar.setVisibility(View.GONE);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    void loadPage(String url) {
        urlo = url;
        if (url.indexOf("://") == -1) {
            url = "http://" + url;
        }
        // editText1.setText(url);
        AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", url);
        IMM.hideSoftInputFromWindow(binding.editTextUrl.getWindowToken(), 0);
        binding.editTextSearch.setText("");
        list_webView.get(currentPage).loadUrl(url);
        // btnBack.setEnabled(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
        if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
        if (requestCode == 0) {
            if (intent != null)
                list_webView.get(currentPage).loadUrl(intent.getStringExtra("url"));
        }
        if (requestCode == FILECHOOSER_DOWNLOAD_PATH) {
            if (resultCode == Activity.RESULT_OK) { //是否选择，没选择就不会继续
                Uri uri = intent.getData();   // 得到uri，后面就是将uri转化成file的过程。
                //String scheme = uri.getScheme();
                AutoLog.e("uri", uri.toString());
                String[] projection = {"_data"};
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                if (cursor != null) {
                    int column_index = cursor.getColumnIndexOrThrow("_data");
                    cursor.moveToFirst();
                    String filepath = cursor.getString(column_index);
                    AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", filepath);
                    int endIndex = filepath.lastIndexOf("/");
                    if (endIndex != -1) {
                        String path = filepath.substring(0, endIndex);
                        AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", path);
                        downloadBinding.editTextDownloadPath.setText(path);
                    }

                }
            }
        }
    }

    boolean isNetworkConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onPause() {
        AutoLog.v("生命周期->暂停");
        if (isFullScreen) {
            binding.buttonPlay.setVisibility(View.VISIBLE);
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        AutoLog.v("生命周期->恢复");
        if (webSettings != null) {
            webSettings.setBlockNetworkImage(sharedPreferences.getBoolean("switch_no_images", false));//无图模式
        }
    }

    void pauseVideo() {
        String js = "javascript:var obj = document.getElementsByTagName('video');for (var i = 0; i < obj.length; i++) { obj[i].pause();}";
        list_webView.get(currentPage).loadUrl(js);
    }

    void playVideo() {
        String js = "javascript:var obj = document.getElementsByTagName('video');for (var i = 0; i < obj.length; i++) { obj[i].play();}";
        list_webView.get(currentPage).loadUrl(js);
    }

    private void MenuDialog() {
        String[] items = {"新建窗口", "关闭当前窗口", "收藏当前页", "收藏夹", "查找", "分享", "视频独立播放", "视频截图", "视频在播放器中打开", "查看源码", "主页", "全屏", "广告过滤规则", "设置", "关于", "退出", "清除缓存", "资源列表", "重载列表"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("菜单");
        builder.setIcon(R.drawable.ic_launcher);
        builder.setItems(items, (dialog, which) -> {
            dialog.dismiss();
            switch (which) {
                case 0:
                    newWindow(sharedPreferences.getString("homepage", "http://www.baidu.com"));
                    break;
                case 1:
                    closeCurrentPage();
                    break;
                case 2:
                    collectionPage();
                    break;
                case 3:
                    Intent intent = new Intent(MainActivity.this, FavoriteActivity.class);
                    startActivityForResult(intent, 0);
                    break;
                case 4:
                    binding.searchBar.setVisibility(View.VISIBLE);
                    binding.editTextSearch.requestFocus();
                    list_webView.get(currentPage).findAllAsync(binding.editTextSearch.getText().toString());
                    break;
                case 5:
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_SEND);
                    intent.putExtra(Intent.EXTRA_TEXT, list_webView.get(currentPage).getUrl());
                    intent.setType("text/plain");
                    startActivity(Intent.createChooser(intent, "分享"));
                    break;
                case 6:
                    String js = "javascript:var videos=document.getElementsByTagName('video'); if(videos.length!=0){ var url=videos[0].src;window.location.href=url; } else { var iframes=document.getElementsByTagName('iframe'); if(iframes.length!=0) window.location.href=iframes[0].src; }";
                    list_webView.get(currentPage).loadUrl(js);
                    break;
                case 7:
                    videoScreenshot();
                    break;
                case 8:
                    videoPlayer();
                    break;
                case 9://改多标签后失效
                    js = "javascript:JSI.processHTML(document.documentElement.outerHTML);";
//                    js = "javascript:var s='<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'; document.body.innerHTML=''; var pre=document.createElement('pre'); document.body.appendChild(pre); pre.textContent=s;";
                    list_webView.get(currentPage).loadUrl(js);
                    break;
                case 10:
                    list_webView.get(currentPage).loadUrl(sharedPreferences.getString("homepage", ""));
                    break;
                case 11:
                    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    binding.LinearLayout2.setVisibility(View.GONE);
                    binding.progressBar1.setVisibility(View.GONE);
                    isFullScreen = true;
                    break;
                case 12:
                    DialogBlockList();
                    break;
                case 13:
                    startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                    break;
                case 14:
                    newWindow("file:///android_asset/about.htm");
                    break;
                case 15:
                    unregisterReceiver(receiver);
                    MainActivity.this.finish();
                    break;
                case 16:
                    list_webView.get(currentPage).clearCache(true);
                    break;
                case 17://资源列表
                    Intent intent1 = new Intent(MainActivity.this, ResourcesActivity.class);
                    intent1.putParcelableArrayListExtra("resList", resourcesList.get(currentPage));
                    startActivityForResult(intent1, 101);
                    break;
                case 18://重载列表
                    Intent intent2 = new Intent(MainActivity.this, ReloadUrlsActivity.class);
                    intent2.putParcelableArrayListExtra("resList", resourcesList.get(currentPage));
                    startActivityForResult(intent2, 102);
            }
        });
        builder.create().show();
    }

    /**
     * 关闭当前页面
     */
    private void closeCurrentPage() {
        list_webView.remove(currentPage);
        currentUrlList.remove(currentPage);
        resourcesList.remove(currentPage);
        if (list_webView.size() == 0) {
            newWindow(sharedPreferences.getString("homepage", "http://www.baidu.com"));
        } else {
            currentPage--;
            if (currentPage < 0) currentPage = 0;
            binding.buttonPage.setText(currentPage + 1 + "");
            binding.webViewLayout.removeAllViews();
            WebView webView = list_webView.get(currentPage);
            binding.webViewLayout.addView(webView);
            binding.buttonTitle.setText(webView.getTitle());
            binding.editTextUrl.setText(webView.getUrl());
            binding.imageButtonInfo.setImageBitmap(webView.getFavicon());
        }
    }

    /**
     * 在播放器中播放视频
     */
    private void videoPlayer() {
        String js;//网址正确，运行崩溃，本地播放器没有注册网络视频类型？
        js = "javascript:function getVideoUrl(){var video_url='';var videos=document.getElementsByTagName('video');if(videos.length==0){var iframe=document.getElementsByTagName('iframe');videos=iframe[0].contentWindow.document.getElementsByTagName('video');}else{video_url=videos[0].src;}return video_url;}";
        list_webView.get(currentPage).loadUrl(js);
        list_webView.get(currentPage).evaluateJavascript("javascript:getVideoUrl()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", "" + value);
                if (!"null".equals(value)) {
                    try {
                        Intent intent1 = new Intent(Intent.ACTION_VIEW);
                        String type = "video/*";
                        Uri uri = Uri.parse(value);
                        intent1.setDataAndType(uri, type);
                        startActivity(intent1);
                    } catch (ActivityNotFoundException e) {
                        AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", "" + e);
                        Toast.makeText(getApplicationContext(), "系统默认播放器不能打开视频", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    /**
     * 视频截图
     */
    private void videoScreenshot() {
        String js;
        js = "javascript:function capture(){var videos=document.getElementsByTagName('video');if(videos.length==0){var iframe=document.getElementsByTagName('iframe');videos=iframe[0].contentWindow.document.getElementsByTagName('video');}var canvas=document.createElement('canvas');videos[0].crossOrigin='*';canvas.width=videos[0].videoWidth;canvas.height=videos[0].videoHeight;canvas.getContext('2d').drawImage(videos[0],0,0,canvas.width,canvas.height);var s = canvas.toDataURL('image/jpeg',1.0); return s;}";
        list_webView.get(currentPage).loadUrl(js);
        list_webView.get(currentPage).evaluateJavascript("javascript:capture()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", value);
                if (!"null".equals(value)) {
                    //字符串转Bitmap，https://www.jianshu.com/p/c9a18050a249
                    byte[] bitmapArray = Base64.decode(value.split(",")[1], Base64.DEFAULT);
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
                    LinearLayout layout = new LinearLayout(MainActivity.this);
                    layout.setOrientation(LinearLayout.VERTICAL);
                    ImageView imageView = new ImageView(MainActivity.this);
                    imageView.setImageBitmap(bitmap);
                    layout.addView(imageView);
                    AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
                    builder1.setTitle("视频截图(" + bitmap.getWidth() + "X" + bitmap.getHeight() + ")");
                    builder1.setView(layout);
                    builder1.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator + "Screenshots";
                            File temp = new File(dir);  // 如果文件夹不存在则创建
                            if (!temp.exists()) {
                                temp.mkdir();
                            }
                            Date date = new Date();
                            SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss");
                            String stime = SDF.format(date);
                            String path = dir + stime + ".jpg";
                            File file = new File(path);
                            BufferedOutputStream BOS = null;
                            try {
                                BOS = new BufferedOutputStream(new FileOutputStream(file));
                            } catch (FileNotFoundException e) {
                                AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", "" + e);
                            }
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, BOS);
                            try {
                                BOS.flush();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                BOS.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            Toast.makeText(getApplicationContext(), "保存到：" + path, Toast.LENGTH_SHORT).show();
                            MediaScannerConnection.scanFile(MainActivity.this, new String[]{path}, null, null);
                        }
                    });
                    builder1.setNegativeButton("关闭", (dialog, which) -> {
                    });
                    builder1.create().show();
                } else {
                    Toast.makeText(getApplicationContext(), "请先播放视频或把视频独立播放", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 收藏页面
     */
    private void collectionPage() {
        LinearLayout layout = new LinearLayout(MainActivity.this);
        layout.setOrientation(LinearLayout.VERTICAL);
        final EditText ET_title = new EditText(MainActivity.this);
        ET_title.setHint("标题");
        ET_title.setText(list_webView.get(currentPage).getTitle());
        layout.addView(ET_title);
        final EditText ET_url = new EditText(MainActivity.this);
        ET_title.setHint("网址");
        ET_url.setText(list_webView.get(currentPage).getUrl());
        layout.addView(ET_url);

        AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
        Bitmap icon = list_webView.get(currentPage).getFavicon();
        if (icon == null) {
            icon = BitmapFactory.decodeResource(getResources(), R.drawable.network);
        }
        Matrix matrix = new Matrix();
        matrix.postScale((float) 100 / icon.getWidth(), (float) 100 / icon.getHeight());
        Bitmap bitmap = Bitmap.createBitmap(icon, 0, 0, icon.getWidth(), icon.getHeight(), matrix, true);
        BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
        builder1.setIcon(drawable);
        builder1.setTitle("添加收藏");
        builder1.setView(layout);
        builder1.setPositiveButton("确定", (dialog1, which1) -> {
            String stitle = ET_title.getText().toString();
            String surl = ET_url.getText().toString();
            Field field = null;
            try {
                //通过反射获取dialog中的私有属性mShowing
                field = dialog1.getClass().getSuperclass().getDeclaredField("mShowing");
                field.setAccessible(true);//设置该属性可以访问
            } catch (Exception ignored) {

            }
            if (!stitle.equals("") && (surl.startsWith("http") || surl.startsWith("file:///"))) {
                App.getInstance().getDaoSession().getFavoriteTabDao().insertOrReplace(new FavoriteTab(surl, stitle));
                IMM.hideSoftInputFromWindow(ET_title.getWindowToken(), 0);
                try {
                    field.set(dialog1, true);//关闭
                    dialog1.dismiss();
                } catch (Exception ignored) {
                }
            } else {
                if (stitle.equals("")) {
                    ET_title.setError("标题不能为空！");
                }
                if (!surl.startsWith("http") || !surl.startsWith("file:///")) {
                    ET_url.setError("网址错误！");
                }
                try {
                    //设置dialog不可关闭
                    field.set(dialog1, false);
                    dialog1.dismiss();
                } catch (Exception ignored) {
                }
            }
        });
        builder1.setNegativeButton("取消", (dialog, which) -> {
            IMM.hideSoftInputFromWindow(ET_title.getWindowToken(), 0);
            Field field = null;
            try {
                //通过反射获取dialog中的私有属性mShowing
                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                field.setAccessible(true);//设置该属性可以访问
            } catch (Exception ignored) {
            }
            try {
                field.set(dialog, true);
                dialog.dismiss();
            } catch (Exception ignored) {
            }
        });
        builder1.create().show();
    }

    void DialogBlock(String content) {
        final EditText ETrule = new EditText(this);
        ETrule.setText(content);
        final AlertDialog dialogRule = new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("屏蔽规则").setView(ETrule).setCancelable(false).setPositiveButton("添加", null).setNeutralButton("删除", null).setNegativeButton("取消", null).create();
        dialogRule.show();
        dialogRule.getButton(AlertDialog.BUTTON_POSITIVE)
                .setOnClickListener(v -> {
                            boolean exist = false;
                            String rule = ETrule.getText().toString();
                            List<String> rulelist = new ArrayList<>(Arrays.asList(FileUtil.ReadFile(MainActivity.this, "blockrules").split("\n")));
                            for (int i = 0; i < rulelist.size(); i++) {
                                if (rulelist.get(i).equals(rule)) {
                                    Toast.makeText(MainActivity.this, "此条规则已经存在！", Toast.LENGTH_SHORT).show();
                                    exist = true;
                                    break;
                                }
                            }
                            if (!exist) {
                                boolean blockrules = FileUtil.addRule(MainActivity.this, "blockrules", rule);
                                if (blockrules) {
                                    ADBlock();
                                }
                                dialogRule.dismiss();
                            }
                        }
                );
        dialogRule.getButton(AlertDialog.BUTTON_NEUTRAL)
                .setOnClickListener(v -> {
                            String rule = ETrule.getText().toString();
                            List<String> rulelist = new ArrayList<>(Arrays.asList(FileUtil.ReadFile(MainActivity.this, "blockrules").split("\n")));
                            for (int i = 0; i < rulelist.size(); i++) {
                                if (rulelist.get(i).equals(rule)) {
                                    rulelist.remove(i);
                                    break;
                                }
                            }
                            StringBuilder content1 = new StringBuilder();
                            for (int i = 0; i < rulelist.size(); i++) {
                                content1.append(rulelist.get(i)).append("\n");
                            }
                            FileOutputStream outStream;
                            try {
                                outStream = MainActivity.this.openFileOutput("blockrules", Context.MODE_PRIVATE);
                                outStream.write(content1.toString().getBytes());
                                outStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            dialogRule.dismiss();
                            ADBlock();
                        }
                );
        dialogRule.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(v -> dialogRule.dismiss());
    }

    void DialogBlockList() {
        final String[] datas = FileUtil.ReadFile(MainActivity.this, "blockrules").split("\n");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, datas);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("屏蔽规则列表：");
        builder.setAdapter(adapter, (dialog, which) -> DialogBlock(datas[which]));
        builder.setPositiveButton("确定", (dialog, which) -> {
        });
        builder.setNeutralButton("清空", (dialog, which) -> {
            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
            builder1.setMessage("操作不可逆，确认清空吗？");
            builder1.setIcon(R.drawable.ic_launcher);
            builder1.setTitle("警告");
            builder1.setPositiveButton("确认", (dialog12, which12) -> {
                String filepath = getFilesDir().getAbsolutePath() + "/blockrules";
                File file = new File(filepath);
                //if(file.isFile() && file.exists()) {
                AutoLog.e(String.valueOf(file.delete()));
                //}
            });
            builder1.setNegativeButton("取消", (dialog1, which1) -> {
            });
            builder1.create().show();
        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 无图模式
     */
    private void noImages(boolean isNoImg) {
        String js;
        if (isNoImg) {
            js = "javascript:var img=document.getElementsByTagName('img'); for(i=0;i<img.length;i++){img[i].style.display='none';} ";
        } else {
            js = "javascript:var img=document.getElementsByTagName('img'); for(i=0;i<img.length;i++){img[i].style.display='';}";
        }
        list_webView.get(currentPage).loadUrl(js);
    }

    /**
     * 广告过滤
     */
    private void ADBlock() {
        String s = FileUtil.ReadFile(MainActivity.this, "blockrules");
        if (!"".equals(s)) {
            String rules = s.replace("\n", ",");
            if (rules.endsWith(",")) {
                rules = rules.substring(0, rules.length() - 1);
            }
            String js = "javascript:var rules='" + rules + "';var rule=new Array();rule=rules.split(',');var img=document.getElementsByTagName('img');for(i=0;i<img.length;i++){for(j=0;j<rule.length;j++){if(img[i].src.indexOf(rule[j])!=-1){img[i].style.display='none';}}}";
            list_webView.get(currentPage).loadUrl(js);
        }
    }

    /**
     * 网页框架过滤
     */
    private void iframeBlock() {
        String js = "javascript:var iframes=document.getElementsByTagName('iframe');for(i=0;i<iframes.length;i++){iframes[i].style.display='none';}document.getElementById('win-pop-foot').style.display='none';document.getElementById('win-pop-foot1').style.display='none';";
        list_webView.get(currentPage).loadUrl(js);
    }

    // 调用系统下载，https://www.jianshu.com/p/6e38e1ef203a
    private void downloadBySystem(String surl, String contentDisposition, String mimeType, String path, String fileName) {
        // 指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(surl));
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
        // request.setTitle("This is title");
        // 设置通知栏的描述
        request.setDescription(surl);
        // 允许该记录在下载管理界面可见
        //request.setVisibleInDownloadsUi(true);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 设置下载文件保存的路径和文件名
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        // 自定义下载路径
        //request.setDestinationUri();
        //request.setDestinationInExternalFilesDir();
        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
        AutoLog.v("下载id:" + downloadId);
    }

    /**
     * 下载完成接收器
     */
    private class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            AutoLog.v("下载完成接收器:", intent != null ? intent.toUri(0) : null);
            if (intent != null) {
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", downloadId + "");
                    DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                    if (downloadId == downloadIdUpdate) {
                        Uri uri = downloadManager.getUriForDownloadedFile(downloadId);
                        AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", uri.toString());
                        Intent intent1 = new Intent(Intent.ACTION_VIEW);
                        intent1.setDataAndType(uri, "application/vnd.android.package-archive");
                        startActivity(intent1);
                    }
                }
            }
        }
    }

    /**
     * 新建窗口
     *
     * @param surl
     */
    private void newWindow(String surl) {
        WebView webView = new WebView(MainActivity.this);
        webView.addJavascriptInterface(new MyJSInterface(), "JSI");
        settingWebView(webView);
        webView.loadUrl(surl);

        binding.webViewLayout.removeAllViews();
        binding.webViewLayout.addView(webView);
        list_webView.add(webView);
        currentUrlList.add(surl);
        currentPage = list_webView.size() - 1;
        resourcesList.add(new ArrayList<>());
        binding.buttonPage.setText(currentPage + 1 + "");
    }

    @SuppressLint("ClickableViewAccessibility")
    void settingWebView(WebView webView) {
        registerForContextMenu(webView); // 注册菜单
        webView.requestFocusFromTouch(); // 请求触摸焦点
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);   // 允许调试
        }

        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true); // 开启JS
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); // 允许JS打开窗口
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); // 开启缓存
        // 自适应屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(true); // 支持缩放
        webSettings.setBuiltInZoomControls(true); // 启用内置缩放控件
        webSettings.setDisplayZoomControls(false); // 隐藏缩放控件
        webSettings.setAllowFileAccess(true); // 开启文件访问
        webSettings.setDatabaseEnabled(true); // 开启数据库
        webSettings.setDomStorageEnabled(true); // 开启localStorage
        webSettings.setGeolocationEnabled(true); // 开启定位
        webSettings.setSupportMultipleWindows(true); // 支持多窗口
        webSettings.setAllowUniversalAccessFromFileURLs(true); // 允许跨域
        webSettings.setBlockNetworkImage(sharedPreferences.getBoolean("switch_no_images", false));//无图模式

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);  // 允许HTTPS、HTTP混合内容
        }
        if (sharedPreferences.getBoolean("switch_pcmode", false)) {
            webSettings.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        }

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                AutoLog.v("重载url:" + url);
                // 协议过滤
                if (url.startsWith("http") || url.startsWith("ftp://") && !url.startsWith("https://cdn-haokanapk.baidu.com/")) {
                    if (url.startsWith("https://baiduyunbo.com/?id=")) {
                        String id = url.replace("https://baiduyunbo.com/?id=", "");
                        view.loadUrl("https://m3u8.cdnpan.com/" + id + ".m3u8");
                    } else {
                        view.loadUrl(url);
                    }
                    return false;
                }
                return true; //不跳转
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if (sharedPreferences.getBoolean("switch_jsonp_res", false)) {//拦截跨域资源
                    String currentUrl = currentUrlList.get(currentPage);
                    String host = currentUrl.substring(currentUrl.indexOf("//") + 2);
                    if (host.contains("/")) {
                        host = host.substring(0, host.indexOf("/"));
                    }
                    String runUrl = request.getUrl().toString();
                    String runHost = runUrl.substring(runUrl.indexOf("//") + 2);
                    if (runHost.contains("/")) {
                        runHost = runHost.substring(0, runHost.indexOf("/"));
                    }
                    if (!runHost.contains(host)) {
                        AutoLog.v("拦截的资源:" + runUrl);
                        return null;
                    }
                }
                AutoLog.v("允许通过资源：" + request.getUrl().toString());
                resourcesList.get(currentPage).add(new ResourcesBean(request.getUrl().toString(), false));
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                AutoLog.v("页面开始加载:" + url);
                currentUrlList.set(currentPage, url);//更新当前页面
                resourcesList.get(currentPage).clear();
                binding.buttonTitle.setText(url);
                binding.buttonTitle.setVisibility(View.VISIBLE);
                binding.editTextUrl.setText(url);
                binding.editTextUrl.setVisibility(View.GONE);
                urln = url;
                binding.buttonBack.setEnabled(true);
                IMM.hideSoftInputFromWindow(binding.editTextUrl.getWindowToken(), 0);
                binding.progressBar1.setVisibility(View.VISIBLE);
                binding.imageButtonInfo.setImageResource(android.R.drawable.ic_menu_info_details);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                AutoLog.v("页面加载完成：" + url);
                binding.progressBar1.setVisibility(View.INVISIBLE);
//                noImages(sharedPreferences.getBoolean("switch_no_images", false));
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Toast.makeText(getApplicationContext(), "ReceivedError:" + errorCode, Toast.LENGTH_SHORT).show();
                if (isNetworkConnected()) {
                    switch (errorCode) {
                        case WebViewClient.ERROR_HOST_LOOKUP:   // 找不到主机，跳转百度搜索
                            AutoLog.v("接收错误，找不到主机：" + failingUrl);
                            String url = "http://m.baidu.com/s?word=" + urlo;
                            binding.editTextUrl.setText(url);
                            view.loadUrl(url);
                            urln = url;
                            break;
                        case WebViewClient.ERROR_UNSUPPORTED_SCHEME:
                            AutoLog.v("接收错误，不支持的协议：" + failingUrl);
                    }
                } else {
                    view.loadDataWithBaseURL(
                            "",
                            "<html><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"/><title>网络未连接</title><style>h1{font-size:10vw;margin:40vh auto;text-align:center;}</style><body><h1>网络未连接</h1></body></html>",
                            "text/html", "utf-8", "");
                }
            }

            //在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
//                AutoLog.v("加载资源：" + url);
            }
        });

        webView.setFindListener((activeMatchOrdinal, numberOfMatches, isDoneCounting) -> {
            if (numberOfMatches == 0) {
                binding.textViewSearchCount.setText(activeMatchOrdinal + "/" + numberOfMatches);
            } else {
                binding.textViewSearchCount.setText(activeMatchOrdinal + 1 + "/" + numberOfMatches);
            }
        });

        webView.setDownloadListener(new MyWebViewDownLoadListener());
        webView.setOnTouchListener((v, event) -> {
            binding.buttonTitle.requestFocus();
            binding.buttonTitle.setVisibility(View.VISIBLE);
            binding.editTextUrl.setVisibility(View.GONE);
            IMM.hideSoftInputFromWindow(binding.editTextUrl.getWindowToken(), 0);
            return false;
        });
        webView.setWebChromeClient(new MyWebChromeClient());
    }


    class MyWebChromeClient extends WebChromeClient {
        // JS的alert('')提示信息转换成安卓控件提示信息
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            result.confirm();
            return true;
        }

        // HTML5.input.file转换为安卓文件选择器
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
            openFileChooserImplForAndroid5(uploadMsg);
            return true;
        }

        // 进度条
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
//            AutoLog.v("进度加载完成" + newProgress);
            binding.progressBar1.setProgress(newProgress);
            //广告
            if (sharedPreferences.getBoolean("switch_adBlock", false)) {
                ADBlock();
            }
            //过滤关键字
            if (sharedPreferences.getBoolean("switch_iframeBlock", false)) {
                if (view.getUrl() != null) {
                    if (!view.getUrl().contains("baidu.com")) {
                        iframeBlock();
                    }
                }
            }
            // 链接关键字屏蔽
            if (sharedPreferences.getBoolean("switch_filter", false)) {
                String sf = sharedPreferences.getString("filter", "");
                if (!sf.equals("")) {
                    String js = "javascript:var s='" + sf + "';var sl=s.split(';');var a=document.getElementsByTagName('a');for(var i=0;i<a.length;i++){for(var j=0;j<sl.length;j++){if(a[i].textContent.indexOf(sl[j])!=-1){a[i].textContent='';}}}";
                    view.loadUrl(js);
                }
            }
            // 链接关键字高亮
            if (sharedPreferences.getBoolean("switch_highlight", false)) {
                String shl = sharedPreferences.getString("highlight", "");
                if (!shl.equals("")) {
                    String js = "javascript:var s='" + shl + "';var sl=s.split(';');var a=document.getElementsByTagName('a');for(var i=0;i<a.length;i++){for(var j=0;j<sl.length;j++){if(a[i].textContent.indexOf(sl[j])!=-1){a[i].style.color='white';a[i].style.backgroundColor='#DA3434';}}}";
                    view.loadUrl(js);
                }
            }
            //图片宽度超出父元素适应父元素
            if (sharedPreferences.getBoolean("switch_shrink", false)) {
                String js = "javascript:var imgs=document.getElementsByTagName('img');for(var i=0;i<imgs.length;i++){if(imgs[i].parentNode.clientWidth > 0){if(imgs[i].clientWidth>imgs[i].parentNode.clientWidth){imgs[i].width=imgs[i].parentNode.clientWidth;}}}";
                view.loadUrl(js);
            }
        }

        // 获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            binding.buttonTitle.setText(title);
            ptitle = title;
        }

        // 接收网站图标(favicon)
        public void onReceivedIcon(WebView view, Bitmap icon) {
            binding.imageButtonInfo.setImageBitmap(icon);
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            AutoLog.v("js规则：" + url + "\n 消息：" + message + "\n 规则：" + result);
            return super.onJsBeforeUnload(view, url, message, result);
        }

        // 播放网络视频时全屏会被调用的方法
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            AutoLog.v("播放网络视频-全屏");
            customViewCallback = callback;
            // 将video放到当前视图中
            binding.videoLayout.addView(view);
            // 设置全屏
            setFullScreen();
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }

        // 视频播放退出全屏会被调用的
        @Override
        public void onHideCustomView() {
            AutoLog.v("播放网络视频-退出全屏");
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            // 退出全屏
            // quitFullScreen();
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
//            AutoLog.v("控制台事件：", consoleMessage.message() + " at " + consoleMessage.sourceId() + ":" + consoleMessage.lineNumber());
            return super.onConsoleMessage(consoleMessage);
        }

        // 定位权限
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        // target="_blank" 处理
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            AutoLog.v("新窗口中打开：", isDialog, isUserGesture, resultMsg);
            if (isUserGesture) {
                WebView webView = new WebView(MainActivity.this);
                settingWebView(webView);
                binding.webViewLayout.removeAllViews();
                binding.webViewLayout.addView(webView);
                list_webView.add(webView);
                currentUrlList.add(view.getOriginalUrl());
                currentPage = list_webView.size() - 1;
                binding.buttonPage.setText(currentPage + 1 + "");
                resourcesList.add(new ArrayList<>());
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(webView);
                resultMsg.sendToTarget();
            }
            return true;
        }
    }

    void getDataFromIntent(Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_VIEW)) {
            urln = intent.getDataString();
            newWindow(urln);
        } else {
            newWindow(sharedPreferences.getString("homepage", "http://www.baidu.com"));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getIntent().getDataString() != null) {
            urln = getIntent().getDataString();
            AutoLog.e(Thread.currentThread().getStackTrace()[2] + "", "onNewIntent(" + urln + ")");
            newWindow(urln);
        }
    }

    void dialog_download(final String surl, String contentDisposition, String mimeType, long contentLength) {
        downloadBinding = DialogDownloadBinding.inflate(LayoutInflater.from(this));
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_download, null, false);
        final EditText editText_download_url = (EditText) view.findViewById(R.id.editText_download_url);
        editText_download_url.setText(surl);
        final EditText editText_download_filename = (EditText) view.findViewById(R.id.editText_download_filename);
        String filename = surl.substring(surl.lastIndexOf("/") + 1);
        AutoLog.v("弹窗下载 FileName: " + filename);
        if (filename.contains("&f=JPEG?")) {//百度网页图片重命名
            SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            String stime = SDF.format(date);
            filename = stime + ".jpg";
        } else {
            filename = URLUtil.guessFileName(surl, null, null);
        }
        editText_download_filename.setText(filename);
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
        downloadBinding.editTextDownloadPath.setText(path);
        ImageButton imageButton_path = (ImageButton) view.findViewById(R.id.imageButton_path);

        imageButton_path.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            startActivityForResult(intent, FILECHOOSER_DOWNLOAD_PATH);
        });

        if (contentLength == 0) {
            GetFileLengthThread getFileLengthThread = new GetFileLengthThread();
            getFileLengthThread.surl = editText_download_url.getText().toString();
            getFileLengthThread.start();
        } else {
            downloadBinding.textViewFilesize.setText(Formatter.formatFileSize(MainActivity.this, contentLength));
        }

        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("新建下载")
                .setIcon(android.R.drawable.stat_sys_download)
                .setView(view)
                .setPositiveButton("确定", (dialog1, which) -> {
                    String url = editText_download_url.getText().toString();
                    if (!url.equals("")) {
                        downloadBySystem(url, "", URLConnection.getFileNameMap().getContentTypeFor(url), "", editText_download_filename.getText().toString());
                        IMM.hideSoftInputFromWindow(editText_download_filename.getWindowToken(), 0);
                    }
                })
                .setNegativeButton("取消", (dialog12, which) -> {
                })
                .create();
        dialog.show();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    downloadBinding.textViewFilesize.setText(Formatter.formatFileSize(MainActivity.this, msg.arg1));
                    break;
            }
        }

        ;
    };

    class GetFileLengthThread extends Thread {
        String surl;

        public void run() {
            int fileLength = 0;
            URL url = null;
            try {
                url = new URL(surl);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            HttpURLConnection urlcon;
            try {
                urlcon = (HttpURLConnection) url.openConnection();
                fileLength = urlcon.getContentLength();

            } catch (IOException e) {
                e.printStackTrace();
            }
            Message message = Message.obtain();
            message.what = 0;
            message.arg1 = fileLength;
            handler.sendMessage(message);
        }
    }
}